﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DemoForm.BLL
{
    public delegate bool MoveDelagate();

    public class AnimationHelper
    {
        static AnimationHelper animation = new AnimationHelper();

        /// <summary>
        /// 添加一个动画
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="NextLocation"></param>
        public static void AddMove(Control ctl, Point NextLocation)
        {
            animation.AddAct(() =>
            {
                var lX = NextLocation.X - ctl.Location.X;
                var lY = NextLocation.Y - ctl.Location.Y;
                if (Math.Abs(lX) > 10)
                {
                    lX = lX > 0 ? 10 : -10;
                }
                if (Math.Abs(lY) > 10)
                {
                    lY = lY > 0 ? 10 : -10;
                }
                ctl.Location = new Point(ctl.Location.X + lX, ctl.Location.Y + lY);

                return ctl.Location.X != NextLocation.X || ctl.Location.Y != NextLocation.Y;
            });
        }

        /// <summary>
        /// 开始运行
        /// </summary>
        /// <param name="EndAct">当前队列的所有动画全部运行完毕的回调</param>
        public static void Start(Action EndAct)
        {
            new Action(() =>
                {
                    animation.Start();
                })
                .BeginInvoke((a) => { EndAct(); }, null);
        }

        #region 动画运行
        private System.Timers.Timer timer;
        List<MoveDelagate> ActList = new List<MoveDelagate>();

        private AnimationHelper()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 50;
            timer.Elapsed += Timer_Elapsed;
        }

        private void AddAct(MoveDelagate move)
        {
            this.ActList.Add(move);
        }

        private void Start()
        {
            timer.Enabled = true;
            while (true)
            {
                if (ActList.Count > 0)
                {
                    System.Threading.Thread.Sleep(100);
                    continue;
                }
                break;
            }
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                timer.Enabled = false;
                for(int i=ActList.Count-1;i>=0; i--)
                {
                    var act = ActList[i];
                    var ctn = act.Invoke();
                    if (!ctn)
                    {
                        ActList.RemoveAt(i);
                    }
                }
            }
            catch (Exception)
            {

            }
            finally
            {
                timer.Enabled = ActList.Count > 0;
            }
        }
        #endregion
    }
}
